package cn.edu.scau.cmi.luodongmei.hibernate.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import cn.edu.scau.cmi.luodongmei.hibernate.dao.StudentDAO;
import cn.edu.scau.cmi.luodongmei.hibernate.dao.TeacherDAO;
import cn.edu.scau.cmi.luodongmei.hibernate.domain.Student;
import cn.edu.scau.cmi.luodongmei.hibernate.domain.Teacher;
import cn.edu.scau.cmi.luodongmei.hibernate.service.ConnService;
import cn.edu.scau.cmi.luodongmei.hibernate.util.HibernateUtils;

public class ConnServiceImpl implements ConnService {

	StudentDAO studentDAO = new StudentDAO();
	TeacherDAO teacherDAO = new TeacherDAO();
	
	@Override
	public boolean selectTutor(String sname, String tname) {
		Student stu = studentDAO.findByName(sname);
		Teacher teacher = teacherDAO.findByName(tname);
		Session session = null;
        try {
            session = HibernateUtils.getSession();
            Transaction tx = session.beginTransaction();
            teacher.getStudents().add(stu);
            stu.setTeacher(teacher);
            session.update(teacher);
            tx.commit();
            //System.out.println("success!");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }finally{
        	if(session!=null)
				session.close();
        } 
	}

	@Override
	public List getStudents(String tname) {
		Session session = null;
		try {
			session = HibernateUtils.getSession();
			String queryString = "select s.name from Student as s where s.teacher.name= ?";
			Query queryObject = session.createQuery(queryString);
			queryObject.setParameter(0, tname);
			List stuList = queryObject.list();
			return stuList;
		} catch (RuntimeException re) {
			throw re;
		} finally {
			if(session!=null)
				session.close();
		}
	}


}
